<template>
  <div>
    <!-- 搜索 -->
    <van-search
      v-model="keyword"
      shape="round"
      show-action
      autofocus
      placeholder="请输入搜索关键词"
      @search="onSearch"
    >
      <template #left>
        <van-icon name="arrow-left" @click="$router.back()"/>
      </template>
      <template #action>
        <div @click="Search">搜索</div>
      </template>
    </van-search>
    <div class="card-show">
    <!-- history -->
    <SearchHistory :searchHistories="searchHistories" @onClickDelHistory="onClickDelHistory" @onSearch="searchKeywords" @delAll="removeAllHistory" v-if="isHistory" />
    <!-- hot_search -->
    <HotSearch :hotSearchResList="hotSearchResList" @onSearch="searchKeywords"  v-if="isSearch"/>
    <!-- 联想建议 -->
    <SearchAdvice :searchResList="searchResList" :keyword="keyword" @onSearch="searchKeywords" v-if="isLxjy"/>
    <!-- 搜索结果 -->
    <div class="search-result" v-if="isSearchList">
      <ArticleItem :config="config" :data="articleList"/>
    </div>
  </div>
  </div>

</template>

<script>
import jsonp from 'jsonp'
import _ from 'lodash'
import ArticleItem from '@/components/Article/Article-item.vue'
import SearchHistory from '@/views/Search/components/search-history.vue'
import HotSearch from '@/views/Search/components/hot-search.vue'
import SearchAdvice from '@/views/Search/components/search-advice.vue'
import { setItem, getItem } from '@/utils/storage'
import { getUserHistory, getHotSearch, delRowSearchHistory, delAllSearchHistory, searchKeyword } from '@/api/search'
import { mapGetters } from 'vuex'
// import { getArticleList } from '@/api/article'
export default {
  name: 'Search',
  // props: ['keywords'],
  components: { ArticleItem, SearchHistory, HotSearch, SearchAdvice },
  data () {
    return {
      config: {
        showAuthorName: true,
        showRead: true,
        one: true,
        showAvatar: false
      },
      keyword: '',
      searchResList: [
        '11月8号红月亮月全食',
        '163邮箱登录',
        '1美元兑换多少人民币',
        '1g等于多少mg',
        '1升等于多少毫升',
        '192.1681.1',
        '192.168.0.1 登陆页面',
        '126邮箱',
        '163邮箱',
        '12生肖排序'

      ], // 联想建议数据
      searchHistories: [], // 搜索历史的数据
      hotSearchResList: [], // 热门搜索的数据
      total: 0,
      articleList: {}, // 搜索出来的文章数据
      // keyword: '',
      pageSize: 10,
      pageNum: 1
    }
  },
  watch: {
    keyword (newValue, oldValue) {
      this.debounce()
    },
    searchHistories () {
      setItem('search-histories', this.searchHistories)
    }
  },
  created () {
    this.getUserHistory()
    this.getHotSearch()
    this.loadSearcHistories()
  },
  computed: {
    ...mapGetters(['token']),
    isHistory () {
      return !this.keyword && this.searchHistories.length
    },
    isSearch () {
      return !this.keyword && this.hotSearchResList.length
    },
    isLxjy () {
      return this.keyword && this.searchResList.length && !this.articleList
      // return true
    },
    isSearchList () {
      return this.keyword && this.articleList
    }
  },
  methods: {
    // 监听点击搜索关键词，搜索内容
    searchKeywords (keyword) {
      console.log(keyword)
      this.onSearch(keyword)
    },
    Search (ss) {
      this.onSearch(this.keyword)
    },
    async onSearch (keyword) {
      if (!keyword) return
      this.keyword = keyword
      console.log(keyword)
      this.searchResList = [] // 清空联想建议才能显示搜索结果
      const index = this.searchHistories.indexOf(this.keyword)
      if (index !== -1) {
        // 把重复的删除掉
        this.searchHistories.splice(index, 1)
      }
      // 把最新的搜索历史放到数组最前面
      this.searchHistories.unshift(this.keyword)

      // 如果用户已登录，则把搜索记录存储到数据库（后端已做）
      const res = await searchKeyword({
        keywords: this.keyword,
        pageNum: this.pageNum,
        pageSize: this.pageSize
      })// 用户是否登录后端做了判断
      this.articleList = res
      this.pageNum = res.pageNum
      this.pageSize = res.pageSize
      console.log(`搜索关键词 ： ${this.keyword} 出来的数据：`, res.list)
      // 如果用户未登录，则把搜索记录存储到本地
      // setItem('search-histories', this.searchHistories) // 因为watch监听所以这里可以不用写了
      // 调用api搜索文章
    },

    // 获取热门搜索
    async getHotSearch () {
      const { list } = await getHotSearch({ pageNum: '1', pageSize: '10' })
      this.hotSearchResList = list
    },
    // 获取用户搜索历史
    async getUserHistory () {
      const { list } = await getUserHistory({ pageNum: '1', pageSize: '10' })
      this.searchHistories = list
    },
    // 监听删除单个搜索历史记录操作
    async onClickDelHistory (id) {
      // 1、修改本地存储的数据
      this.searchHistories.splice(id, 1)
      // 2、发api请求删除数据库里的数据
      // 无论是否登录都要把数据持久化到本地存储
      // 如果已登录，则删除线上的历史记录
      // setItem('search-histories', this.searchHistories) // 因为watch监听所以这里可以不用写了
      if (this.token) {
        console.log('用户已登录，发请求删除线上搜索历史记录')
        await delRowSearchHistory(id)
      }
      this.getUserHistory()
    },
    // 清空所有搜索历史记录
    async removeAllHistory () {
      this.searchHistories = []
      // 删除本地数据
      // removeItem('search-histories')
      // 再发请求删除线上数据
      if (this.token) {
        await delAllSearchHistory()
      }
    },
    // 将线上和本地搜索历史记录合并
    async loadSearcHistories () {
      let searcHistories = getItem('search-histories') || []
      if (this.token) {
        const { list } = await getUserHistory()
        const res = list.map((x) => {
          return x.keywords
        })
        // 数组合并后去重
        searcHistories = [...new Set([...searcHistories, ...res])]
      }
      this.searchHistories = searcHistories
    },
    // 防抖
    debounce: _.debounce(function () {
      this.advice()
    }, 400),
    // 发送请求获取联想建议
    advice () {
      if (this.keyword) {
        const url = `http://suggestion.baidu.com/su?wd=${this.keyword}`
        jsonp(url, { param: 'cb' }, (err, data) => {
          if (err) {
            console.error(err.message)
          } else {
            this.searchResList = data.s
          }
        })
      }
    }
  }
}
</script>
<style lang="scss" scoped>
</style>
